﻿using System;
using System.Linq;
using System.Net;
using System.Web.Mvc;
using Service.Infrastructure;
using Service.Infrastructure.Implement;
using Service.Infrastructure.Interface;
using Service.Infrastructure.Result;

namespace Web.Filter
{
    /// <summary>
    /// 异常过滤器
    /// 调用顺序：IAuthorizationFilter>IActionFilter>IResultFilter>IExceptionFilter
    /// </summary>
    public class ExceptionFilter : BaseFilter, IExceptionFilter
    {

        
        public void OnException(ExceptionContext filterContext) //(HttpActionExecutedContext
        {

            ExcptionLogger.Logging(filterContext.Exception, FormatUserVisitMsg(filterContext.HttpContext.Request));

            if (filterContext.HttpContext.Request.IsAjaxRequest()) //(exception is System.Web.HttpException)
            {
                filterContext.Result = AjaxError(filterContext);
            }
            else
            {
                //filterContext.Controller.TempData[Base.ErrorInfo] = MessageResources.Error;
                //TODO：异常的处理，1.返回错误信息，前台自定义显示 2.跳转页面
                filterContext.Result = new RedirectResult("~/Error");//TODO:错误页面路径
            }
            filterContext.ExceptionHandled = true;

        }

        

        

        

        /// <summary>
        ///     Ajax请求的返回错误处理
        /// </summary>
        /// <param name="filterContext"></param>
        /// <returns></returns>
        private JsonResult AjaxError(ExceptionContext filterContext)
        {
            //HTTP:500
            filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
            return new JsonResult
                {
                    Data = new BaseResult(),
                };
        }

    }
}